<template>
  <Layout>
    <div class="fade-in">
      <h2 class="text-2xl font-bold text-gray-800 mb-6">购物车</h2>

      <div v-if="cartItems.length === 0" class="bg-white rounded-xl shadow-sm p-8 text-center text-gray-500">
        <i class="fas fa-shopping-cart text-4xl mb-4"></i>
        <p>您的购物车是空的</p>
        <router-link to="/products" class="text-indigo-600 hover:underline mt-4 inline-block">去购物</router-link>
      </div>

      <div v-else class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 购物车列表 -->
        <div class="lg:col-span-2 bg-white rounded-xl shadow-sm overflow-hidden table-container">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">商品/宠物</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">价格</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">数量</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">小计</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="item in cartItems" :key="item.id" class="hover:bg-gray-50">
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="flex items-center">
                    <img v-if="item.item.image_url" class="w-10 h-10 rounded-full mr-4" :src="item.item.image_url" :alt="item.item.name" />
                    <div>
                      <div class="text-sm font-medium text-gray-900">{{ item.item.name }}</div>
                      <div class="text-sm text-gray-500">{{ item.item.type === 'pet' ? '宠物' : '商品' }}</div>
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">¥{{ item.item.price.toFixed(2) }}</td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <input
                    type="number"
                    v-model.number="item.quantity"
                    @change="updateItemQuantity(item)"
                    min="1"
                    class="w-16 border rounded-md text-center focus:outline-none focus:border-indigo-500 p-1"
                  />
                </td>
                <td class="px-6 py-4 whitespace-nowrap">¥{{ (item.item.price * item.quantity).toFixed(2) }}</td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <button
                    @click="removeItem(item.id)"
                    class="text-red-600 hover:text-red-900"
                  >
                    移除
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 订单总结 -->
        <div class="lg:col-span-1 bg-white rounded-xl shadow-sm p-6 summary-card">
          <h3 class="text-lg font-semibold text-gray-800 mb-4">订单总结</h3>
          <div class="space-y-4">
            <div class="flex justify-between">
              <span class="text-gray-600">商品总数</span>
              <span class="font-medium">{{ totalItems }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600">总金额</span>
              <span class="text-xl font-bold text-indigo-600">¥{{ totalAmount.toFixed(2) }}</span>
            </div>
          </div>
          <button
            @click="createOrder"
            class="btn-primary mt-6 w-full py-3 rounded-lg text-white font-semibold focus:outline-none"
            :disabled="cartItems.length === 0"
            :class="{'opacity-50 cursor-not-allowed': cartItems.length === 0}"
          >
            <i class="fas fa-credit-card mr-2"></i>
            去结算
          </button>
        </div>
      </div>
    </div>
  </Layout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import Layout from '../components/Layout.vue'
import { cartService, orderService } from '../services/api' // 导入购物车和订单服务
import { useRouter } from 'vue-router'

const router = useRouter()
const cartItems = ref([])

// 加载购物车数据
const loadCart = async () => {
  try {
    console.log('Loading cart...'); // 添加日志
    const token = localStorage.getItem('token');
    console.log('Token:', token); // 添加日志
    
    if (!token) {
      console.error('No token found');
      return;
    }
    
    const response = await cartService.getCart();
    console.log('Cart response:', response); // 添加日志
    
    if (Array.isArray(response)) {
      cartItems.value = response;
      console.log('Cart items updated:', cartItems.value); // 添加日志
    } else {
      console.error('Invalid cart response format:', response);
      cartItems.value = [];
    }
  } catch (error) {
    console.error('Failed to load cart:', error);
    if (error.response) {
      console.error('Error response:', error.response.data);
    }
    cartItems.value = [];
  }
}

// 计算总商品数量
const totalItems = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.quantity, 0)
})

// 计算总金额
const totalAmount = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.item.price * item.quantity, 0)
})

// 更新商品数量
const updateItemQuantity = async (item) => {
  try {
    // 确保数量是有效的正整数
    if (item.quantity <= 0 || !Number.isInteger(item.quantity)) {
      alert('数量必须是正整数')
      loadCart() // 刷新购物车以恢复旧值
      return
    }

    await cartService.updateItem(item.id, { quantity: item.quantity })
    alert('更新数量成功')
  } catch (error) {
    console.error('Failed to update item quantity:', error)
    alert(error.response?.data?.error || '更新数量失败')
    loadCart() // 更新失败时刷新购物车以恢复旧值
  }
}

// 从购物车中删除商品
const removeItem = async (id) => {
  try {
    console.log('Removing item:', id); // 添加日志
    await cartService.removeItem(id);
    console.log('Item removed successfully'); // 添加日志
    // 重新加载购物车数据
    await loadCart();
  } catch (error) {
    console.error('Failed to remove item:', error);
    if (error.response) {
      console.error('Error response:', error.response.data);
    }
    alert('删除失败，请重试');
  }
};

// 创建订单
const createOrder = async () => {
  if (!confirm('确定要根据购物车内容创建订单吗？')) {
    return
  }

  try {
    // 从购物车项中提取ID
    const cartItemIds = cartItems.value.map(item => item.id);

    if (cartItemIds.length === 0) {
        alert('购物车为空，无法创建订单');
        return;
    }

    // 发送购物车项ID数组到后端
    const order = await orderService.create({ cart_items: cartItemIds });

    alert('订单创建成功！');
    // 清空本地购物车状态并导航到订单页面
    cartItems.value = [];
    router.push(`/orders/${order.id}`); // 假设后端返回的订单对象中有id

  } catch (error) {
    console.error('Failed to create order:', error);
    alert(error.response?.data?.error || '创建订单失败');
  }
};

onMounted(() => {
  loadCart()
})
</script>

<style scoped>
.table-container {
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  border-radius: 10px;
  overflow: hidden;
}

.table-header {
  background: linear-gradient(135deg, #f8fafc 0%, #edf2f7 100%);
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transition: all 0.3s;
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.btn-primary:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 美化表格 */
table {
  border-collapse: collapse;
  width: 100%;
}

thead tr {
  border-bottom: 1px solid #e0e0e0;
}

th {
  background-color: #f5f5f5; /* 与主内容区背景色一致 */
  color: #616161; /* 深灰色文字 */
  text-align: left;
  padding: 12px 24px; /* 增加内边距 */
  font-weight: 600;
}

tbody tr {
  border-bottom: 1px solid #eeeeee;
}

tbody tr:last-child {
  border-bottom: none;
}

td {
  padding: 12px 24px; /* 增加内边距 */
  vertical-align: middle;
}

tbody tr.hover\:bg-gray-50:hover {
  background-color: #fafafa; /* 浅色悬停背景 */
}

/* 美化订单总结卡片 */
.summary-card {
    border: 1px solid #e0e0e0;
    background-color: #ffffff;
}

.summary-card h3 {
    border-bottom: 1px solid #eeeeee;
    padding-bottom: 16px;
    margin-bottom: 16px;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}

.fade-in {
  animation: fadeIn 0.3s ease-out;
}
</style> 